package proxyTest.serverProxy.client;

import proxyTest.client.ClientHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.net.InetSocketAddress;

/**
 * @Author: jia
 * @Descirption:
 * @Date: 2018/5/16 14:05
 * @Modified By:
 */


public class Client2Server {
    private String ip;
    private int port;
    private Channel channel;
    private Bootstrap b = new Bootstrap();
    private EventLoopGroup worker ;

    public Client2Server() {
    }

    public Client2Server(String ip, int port) {
        this.ip = ip;
        this.port = port;
        getBootstrap(ip, port);

    }
    public Client2Server(String ip, int port,EventLoopGroup worker) {
        this.ip = ip;
        this.port = port;
        this.worker=worker;
        getBootstrap(ip, port);

    }

    private void getBootstrap(String ip, int port) {
        b.group(worker);
        b.channel(NioSocketChannel.class);
        b.remoteAddress(new InetSocketAddress(ip, port));
        b.handler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                ChannelPipeline pipeline = ch.pipeline();
                pipeline.addLast(new StringDecoder());
                pipeline.addLast(new StringEncoder());
                pipeline.addLast(new Client2ServerHandler());

            }
        });
        System.out.println("proxyTest.client====start");
    }

    //启动客户端并不一定要创建连接，等到需要的时候再连接
    public void connect() {

        ChannelFuture fu = null;
        try {
            fu = b.connect().sync();

            Channel channel = fu.channel();
            fu.addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture channelFuture) throws Exception {
                    if(channelFuture.isSuccess()){
                        System.out.println("建立连接成功==");
                    }
                }
            });
            this.channel = channel;
            //channel.closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
            System.out.println("创建连接失败！");
        }
    }

    public void shutdown() {
        worker.shutdownGracefully();
    }

    public void send(Object request) {
        if (channel == null || !channel.isActive()) {
            connect();
        }
        channel.writeAndFlush(request);

    }

    public Channel getChannel() {
        return channel;
    }
}
